/**
 * 每天00：00 删除 File 数据库 标记为 deleted 的数据和文件
 */
const _ = require('lodash');
const queue = require('async/queue');
const fs = require('fs');
module.exports = {
  schedule: {
    immediate: false,
    cron: '0 0 0 * * *', // 每天00：00检查
    type: 'worker', // 指定一个 worker 执行
    env: ['prod'],// 在prod环境才执行
  },
  async task(ctx) {
    let app = ctx.app;
    let {File, Event} = app.model;

    let files = await File.unscoped().findAll({where: {deleted: true}});
    let length = 0;
    let q = queue((file, cb) => {
      let filePath = app.config.screenshot.path + '/' + file.file;
      let smallFile = filePath + '_small';
      try {
        fs.unlinkSync(smallFile);
        length++;
      } catch (e) {

      }
      try {
        fs.unlinkSync(filePath);
        length++;
      } catch (e) {

      }
      file.destroy().then(cb);
    }, 5);

    _.each(files, file => {
      q.push(file);
    });

    //console.log('删除文件任务数量', q.length());
    if (q.length() === 0) {//没有任务
      return await Event.create({value: `每天24点清理系统：删除 0 个文件`, user_id: 1});
    }

    await new Promise(resolve => {
      q.drain = () => {
        //console.log('任务完成，删除文件:', length);
        Event.create({value: `每天24点清理系统：删除 ${length} 个文件`, user_id: 1}).
            then(resolve);
      };
    });

  },
};